package service;

import model.CinemaHall;
import model.Movie;
import model.Show;
import util.FileHandler;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class ShowService {
    private static final String SHOW_FILE = "shows.dat";
    private List<Show> shows;
    private TicketService ticketService;

    public ShowService(TicketService ticketService) {
        this.ticketService = ticketService;
        shows = FileHandler.loadData(SHOW_FILE);
        if (shows == null) shows = new ArrayList<>();
    }

    // 保存场次数据
    public void saveShows() {
        FileHandler.saveData(shows, SHOW_FILE);
    }

    // 列出所有场次
    public List<Show> listAllShows() {
        return new ArrayList<>(shows);
    }

    // 根据ID获取场次
    public Show getShowById(String id) {
        for (Show show : shows) {
            if (show.getId().equals(id)) {
                return show;
            }
        }
        return null;
    }

    // 根据影片ID获取场次
    public List<Show> getShowsByMovieId(String movieId) {
        List<Show> result = new ArrayList<>();
        for (Show show : shows) {
            if (show.getMovieId().equals(movieId)) {
                result.add(show);
            }
        }
        return result;
    }

    // 增加场次（提前一周）
    public boolean addShow(Show show) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 7);
        Date oneWeekLater = calendar.getTime();
        if (show.getTime().after(oneWeekLater)) {
            return false;
        }
        shows.add(show);
        saveShows();
        return true;
    }

    // 修改场次（检查是否有售票）
    public boolean updateShow(Show updatedShow) {
        for (Show show : shows) {
            if (show.getId().equals(updatedShow.getId())) {
                if (ticketService.hasTickets(show.getId())) {
                    return false;
                }
                show.setMovieId(updatedShow.getMovieId());
                show.setTime(updatedShow.getTime());
                show.setPrice(updatedShow.getPrice());
                saveShows();
                return true;
            }
        }
        return false;
    }

    // 删除场次（检查是否有售票）
    public boolean deleteShow(String id) {
        if (ticketService.hasTickets(id)) {
            return false;
        }
        for (int i = 0; i < shows.size(); i++) {
            if (shows.get(i).getId().equals(id)) {
                shows.remove(i);
                saveShows();
                return true;
            }
        }
        return false;
    }

    // 按时间范围列出场次
    public List<Show> getShowsByDays(int days) {
        List<Show> result = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, days);
        Date endTime = calendar.getTime();
        Date now = new Date();
        for (Show show : shows) {
            if (show.getTime().after(now) && show.getTime().before(endTime)) {
                result.add(show);
            }
        }
        return result;
    }

    // 自动排片（高评分影片优先黄金时段）
    public void autoArrangeShows(List<Movie> movies, List<CinemaHall> halls) {
        // 按评分降序排序影片
        movies.sort((m1, m2) -> Double.compare(m2.getScore(), m1.getScore()));

        Calendar calendar = Calendar.getInstance();
        for (int day = 0; day < 7; day++) { // 排一周的片
            calendar.add(Calendar.DAY_OF_MONTH, day);
            for (CinemaHall hall : halls) {
                // 黄金时段：19:00-21:00（周末全天）
                boolean isWeekend = calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
                        || calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY;
                int hour = isWeekend ? 15 : 19; // 周末提前到15点

                calendar.set(Calendar.HOUR_OF_DAY, hour);
                calendar.set(Calendar.MINUTE, 0);
                Date showTime = calendar.getTime();

                // 分配高评分影片
                int movieIndex = (day * halls.size() + halls.indexOf(hall)) % movies.size();
                Movie movie = movies.get(movieIndex);

                // 创建场次
                String showId = "SH" + System.currentTimeMillis() + hall.getName().hashCode();
                Show show = new Show(showId, movie.getId(), hall.getName(), showTime,
                        40 + movie.getScore() * 2, hall); // 评分越高票价越高
                addShow(show);
            }
            calendar.add(Calendar.DAY_OF_MONTH, -day); // 重置日期
        }
    }
}